from bs4 import BeautifulSoup
import requests
import sys
import os
import re
import common.index as common

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
}


def getUrl(word):
    return "https://dict.youdao.com/result?word=%s&lang=en" % word


def getPhoneticOf(word):
    url = getUrl(word)
    print("[Getting]:", url)
    res = requests.get(url, headers=headers)
    soup = BeautifulSoup(str(res.content, "utf8"), "html.parser")

    div = soup.find("div", class_="per-phone")

    # print(type(div), '<-----------')

    if not hasattr(div, "find"):
        if word.find("_") > -1:
            return "".join(getWordsPhonetic(word.split("_"))).replace(" // ", " ")
        else:
            return "/not found /"
    else:
        ele = div.find("span", class_="phonetic")
        # print('phonetic is:', ele.text )
        return ele.text


def getWordsPhonetic(words):
    if isinstance(words, str):
        words = [words]

    result = []
    for index, word in enumerate(words):
        phonetic = getPhoneticOf(word)
        result.append(phonetic)
        print("%d/%d %s: %s" % (index + 1, len(words), word, phonetic))

    return result


def addPhonetic(fname, config):
    absFileName = common.getAbsPath("%s/%s" % (config["dailyDir"], fname), config)

    common.lineLog("正在读取文件 %s, 为其填充音标..." % fname)

    if not os.path.exists(absFileName):
        print("文件 %s 不存在, 请检查输入" % absFileName)
        sys.exit(1)

    with open(absFileName, "r", encoding="utf8") as f:
        lines = f.readlines()

    for index, line in enumerate(lines):
        yushu = index % 3
        if yushu == 1:  # 每组的第二行
            words = [w for w in line.split() if w]
            phoneticList = getWordsPhonetic(words)
            lines[index + 1] = " ".join(phoneticList) + "\n"

    with open(absFileName, "w", encoding="utf8") as fp:
        fp.writelines(lines)

    print("文件更新成功! %s" % absFileName)


# todo
# ----------------------------------------------

startDateStr = "0706"
startDateVal = int(startDateStr)


def getFileList():
    fnameRe = re.compile(r"^words\d{4}\.txt")
    # return [fname for fname in os.listdir('.') if fname.startswith('word') and fname.endswith('txt')]
    return [fname for fname in os.listdir(".") if fnameRe.match(fname)]


def getDateNumber(fileName, toStr=False):
    numRe = re.compile(r"\d+(?=\.)")
    val = numRe.findall(fileName).pop()
    if toStr:
        return val

    return int(val)


def checkPhoneticDone(fileName, config):
    absFilePath = common.getAbsPathOfDailyFile(fileName, config)
    with open(absFilePath, "r", encoding="utf8") as fp:
        lines = fp.readlines()
        isExistsDashLine = any([line.find("---") >= 0 for line in lines])

    return False if isExistsDashLine else True


def autoAddPhonetic(book, config):
    # fileList = getFileList()
    dailyFileList = common.getDailyFilesOfBook(book, config)
    for fileName in dailyFileList:
        done = checkPhoneticDone(fileName, config)
        if not done:
            print("%s 正在添加音标..." % fileName)
            addPhonetic(fileName, config)

    common.lineLog("已添加完音标!")


if __name__ == "__main__":
    # getPhonetic('phonetic')
    getWordsPhonetic(["phonetic", "sound"])
